package com.lin.jdk.juc;

import java.util.Iterator;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream;

/**
 * Test in jdk15
 */
public class ArrayBlockingQueueTest {

    public static void main(String[] args) throws InterruptedException {
        ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(20);
        IntStream.range(1, 21).forEach(i -> queue.add("1--" + UUID.randomUUID().toString()));

        ReentrantLock lock = new ReentrantLock();
        Condition canSet = lock.newCondition();
        new Thread(() -> {
            try {
                lock.lock();
                canSet.await();
                System.out.println(Thread.currentThread().getName() + ">>>>>>>>>>>>>>>>> 等待遍历结束，开始更新队列 >>>>>>>>>>>>>>>");
                IntStream.range(1, 17).forEach(i -> queue.poll());
                IntStream.range(1, 12).forEach(i -> queue.add("2--" + UUID.randomUUID().toString()));
                IntStream.range(1, 15).forEach(i -> queue.poll());
                IntStream.range(1, 12).forEach(i -> queue.add("3--" + UUID.randomUUID().toString()));
                System.out.println(Thread.currentThread().getName() + ">>>>>>>>>>>>>>>>> 更新队列结束 >>>>>>>>>>>>>>>");
                canSet.signalAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "producer").start();

        Iterator<String> it = queue.iterator();
        AtomicInteger count = new AtomicInteger(0);
        new Thread(() -> {
            try {
                lock.lock();
                while (it.hasNext() && count.get() <= 10) {
                    count.incrementAndGet();
                    String obj = it.next();
                    System.out.println(Thread.currentThread().getName() + "tranver -> " + count.get() + " => obj = " + obj);
                }
                canSet.signalAll();
                canSet.await();
                System.out.println("--------------------修改后遍历------------------");
                while (it.hasNext()) {
                    count.incrementAndGet();
                    String obj = it.next();
                    System.out.println(Thread.currentThread().getName() + "tranver -> " + count.get() + " => obj = " + obj);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "tranver").start();

        Thread.currentThread().join();
        System.out.println("---------------------done-------------------");

    }


}
